const base = require("./../../base");
const math = require("mathjs");
const moment = require("moment");
const _ = require("lodash");

math.config({
    number: "BigNumber", // Default type of number:
    // 'number' (default), 'BigNumber', or 'Fraction'
    precision: 20 // Number of significant digits for BigNumbers
});

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
        await super.isShopAuth();
        await super.isUserAuth();
    }

    async _before_add() {
        await super.isShopStatusAuth();
    }
    /**
     *
     * @api {get} /shop/api/shop/order/order/index 订单列表
     * @apiDescription 订单列表
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} status   订单状态
     * @apiParam {Number} page     页码
     *
     * @apiSampleRequest /shop/api/shop/order/order/index
     *
     */
    async index() {
        const { status, page = 1, pay_status } = this.query;
        const shopId = this.state.shop.id;
        const userId = this.state.user.id;
        const order = await this.model("order")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("user_id", userId);
                // qb.where("type", "=", 0); // 普通商品全部订单
                if (this.isSet(status)) {
                    qb.where("status", status);
                }
                if (this.isSet(pay_status)) {
                    qb.where("pay_status", pay_status);
                }
                qb.orderBy("id", "desc");
            })
            .fetchPage({ page, withRelated: ["detail.product", "kuaidi"] });
        this.success(order);
    }

    /**
     *
     * @api {get} /shop/api/shop/order/order/info 订单详情
     * @apiDescription 订单详情
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} id   订单id
     *
     * @apiSampleRequest /shop/api/shop/order/order/info
     *
     */
    async info() {
        const { id } = this.query;
        const shopId = this.state.shop.id;

        const order = await this.model("order")
            .query(qb => {
                qb.where("id", id);
                qb.where("shop_id", shopId);
            })
            .fetch({
                withRelated: [
                    "detail.product",
                    "contact",
                    "service",
                    "verify",
                    "kuaidi",
                    "store"
                ]
            });
        this.success(order);
    }

    /**
     *
     * @api {get} /shop/api/shop/order/order/add 添加订单
     * @apiDescription 添加订单
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Array}  cartdata   购物车数据[{id sku_id num }]
     * @apiParam {Obi}    contact    用户地址
     * @apiParam {Number} couponId   优惠券id
     * @apiParam {Number} sendType   0:送货上门1:到店自提
     * @apiParam {Number} storeId    自提门店id
     * @apiParam {String} remark     备注
     *
     * @apiSampleRequest /shop/api/shop/order/order/add
     *
     */
    async add() {
        const {
            cartdata = [],
            contact = {},
            couponId,
            sendType = 0,
            storeId = 0,
            remark
        } = this.post;
        const shopId = this.state.shop.id;
        const userId = this.state.user.id;
        const wxaId = this.state.wxa.id;
        const orderid =
            moment().format("YYYYMMDDhms") + Math.round(Math.random() * 100);

        let totalpriceOrg = 0;
        let totalprice = 0;
        let coupon_price = 0;
        let coupon_id = 0;
        let full_cut = 0;
        let full_id = 0;
        let full_fee = 0;
        let fee_price = 0;
        let fee_type = 0;
        // llz
        let type = 0; // 0 为普通商品订单，1是分销商品订单
        const fxData = [];
        // llz
        const sku = [];
        for (const key in cartdata) {
            const product = (cartdata[key].product = await this.model("product")
                .query(qb => {
                    qb.where("id", cartdata[key].id);
                    qb.where("status", 1);
                })
                .fetch());
            if (!product) {
                this.fail("商品不存在或已过期");
                return;
            }
            // 查看是否为 分销订单
            // llz
            // const fx_product_info = await this.model("fx_product")
            //     .query(qb => {
            //         qb.where("product_id", "=", product.id);
            //         qb.where("status", "=", 1);
            //         qb.where("shop_id", "=", shopId);
            //         qb.where("type", "=", 0);
            //     })
            //     .fetch();

            // if (fx_product_info && Number(product.type) === 1) {
            //     type = 1;
            // }
            // llz
            if (product.sku_status && cartdata[key].sku_id) {
                const productSku = await this.model("productsku")
                    .query(qb => {
                        qb.where("product_id", product.id);
                        qb.where("id", cartdata[key].sku_id);
                    })
                    .fetch();
                if (!productSku) {
                    this.fail(`商品:${product.name}SKU不存在`);
                    return;
                }
                if (productSku.store < cartdata[key].num) {
                    this.fail(`商品:${product.name}库存不足`);
                    return;
                }
                cartdata[key].sku_name = productSku.sku_name;
                totalpriceOrg = math.format(
                    math.eval(
                        `${totalpriceOrg} + ${productSku.price} * ${
                            cartdata[key].num
                        }`
                    )
                );
                const skuSale =
                    Number(productSku.store) - Number(cartdata[key].num);
                const skuObj = {
                    id: productSku.id,
                    store: skuSale
                };
                sku.push(skuObj);
                cartdata[key].product.price = productSku.price;
            } else {
                totalpriceOrg = math.format(
                    math.eval(
                        `${totalpriceOrg} + ${product.price} * ${
                            cartdata[key].num
                        }`
                    )
                );
            }
            if (!product.fee_type) {
                if (fee_price <= product.fee_price) {
                    fee_price = product.fee_price;
                }
            }
        }
        totalprice = Number(totalpriceOrg);
        const fullCut = await this.model("fullcut")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.orderBy("limit_price", "desc");
            })
            .fetchAll();

        if (fullCut.length) {
            for (let i = 0; i < fullCut.length; i++) {
                if (Number(totalpriceOrg) >= Number(fullCut[i].limit_price)) {
                    full_id = fullCut[i].id;
                    full_cut = fullCut[i].price;
                    full_fee = fullCut[i].free_delivery;
                    break;
                }
            }
        }
        if (Number(full_cut) > 0 && Number(totalpriceOrg) > 0) {
            totalprice = math.format(
                math.eval(`${totalpriceOrg} - ${full_cut}`)
            );
        }

        const coupon = await this.model("user_coupon")
            .query(qb => {
                qb.where("id", couponId);
                // qb.where("status", 0);
            })
            .fetch({
                withRelated: ["coupon"]
            });
        if (couponId) {
            if (!coupon) {
                this.fail("优惠券未发现或已核销");
                return;
            }

            if (coupon.status) {
                this.fail("优惠券已使用");
                return;
            }
            if (
                moment().format("YYYY-MM-DD HH:mm:ss") <
                    moment(coupon.coupon.started_at).format(
                        "YYYY-MM-DD HH:mm:ss"
                    ) ||
                moment(coupon.coupon.ended_at).format("YYYY-MM-DD HH:mm:ss") <
                    moment().format("YYYY-MM-DD HH:mm:ss")
            ) {
                this.fail("优惠券不在有效期");
                return;
            }

            if (coupon.coupon.limit_price > totalpriceOrg) {
                this.fail("优惠券未达到使用条件");
                return;
            }

            if (
                coupon.coupon.id &&
                Number(totalprice) >= Number(coupon.coupon.price)
            ) {
                coupon_id = coupon.coupon.id;
                coupon_price = coupon.coupon.price;
            }
        }
        totalprice = math.format(math.eval(`${totalprice} - ${coupon_price}`));
        if (!full_fee) {
            totalprice = math.format(math.eval(`${totalprice} + ${fee_price}`));
        } else {
            fee_price = 0;
            fee_type = 1;
        }
        const order = await this.model("order")
            .forge({
                shop_id: shopId,
                user_id: userId,
                orderid,
                totalprice,
                totalprice_org: totalpriceOrg,
                pay_status: 0,
                type: 0, // 刚产生订单数据时均为0，当分销的条件都满足时再改变type值，防止不在fx_user表中的用户购买
                send_type: sendType,
                store_id: storeId,
                status: 0,
                remark: remark
            })
            .save();

        for (const key in cartdata) {
            const detail = await this.model("order_detail")
                .forge({
                    user_id: userId,
                    shop_id: shopId,
                    order_id: order.id,
                    product_id: cartdata[key].id,
                    sku_id: cartdata[key].sku_id,
                    sku_name: cartdata[key].sku_name,
                    name: cartdata[key].product.name,
                    num: cartdata[key].num,
                    price: cartdata[key].product.price
                })
                .save();
            const row = {
                order_id: order.id,
                detail_id: detail.id,
                product_id: detail.product_id,
                shop_id: shopId,
                price: detail.price,
                num: cartdata[key].num
            };
            if (type === 1) {
                fxData.push(row);
            }
        }
        if (Number(sendType) === 0) {
            await this.model("order_contact")
                .forge({
                    user_id: userId,
                    shop_id: shopId,
                    order_id: order.id,
                    name: contact.userName,
                    phone: contact.telNumber,
                    address: contact.addr,
                    nationalcode: contact.nationalCode
                })
                .save();
        }
        if (couponId) {
            await this.model("user_coupon")
                .forge({ id: couponId, status: 1 })
                .save();
        }
        await this.model("order_verify")
            .forge({
                order_id: order.id,
                coupon_id: coupon_id,
                coupon_price: coupon_price,
                full_price: full_cut,
                full_id: full_id,
                fee_type: fee_type,
                fee_price: fee_price
            })
            .save();
        const trade = await this.model("trade")
            .forge({
                wxa_id: wxaId,
                user_id: userId,
                tradeid: order.orderid,
                money: totalprice,
                payment: 1,
                status: 0,
                type: 0, // 0表示通过商城购物逻辑的交易，1买单插件模块的交易
                notify_url: process.env.APP_HOST + "/shop/public/public/notfiy"
            })
            .save();
        order.trade_id = trade.id;

        await this.model("order")
            .forge({ id: order.id, trade_id: trade.id })
            .save();
        if (sku.length) {
            await doodoo.bookshelf.Collection.extend({
                model: this.model("productsku")
            }).forge(sku);
        }
        await this.hook.run("addTrade");
        await this.hook.run("print", trade);

        if (type === 1) {
            await this.hook.run(
                "fxMoney",
                fxData,
                userId,
                wxaId,
                shopId,
                order.id
            );
        }
        this.success(order);
    }

    /**
     *
     * @api {get} /shop/api/shop/order/order/update 改变订单状态
     * @apiDescription 改变订单状态
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} status   订单状态
     * @apiParam {Number} id       订单id
     * @apiSampleRequest /shop/api/shop/order/order/update
     *
     */
    async update() {
        const { status, id } = this.query;
        const shopId = this.state.shop.id;
        const userId = this.state.user.id;
        if (!this.isSet(id) || !this.isSet(status)) {
            this.fail("暂无数据");
            return;
        }
        const obj = {
            id: id,
            status: status
        };
        if (Number(status) === 2) {
            const now_data = moment().format("YYYY-MM-DD HH:mm:ss");
            obj.finsh_time = now_data;
        }
        const order = await this.model("order")
            .forge(obj)
            .save();

        this.success(order);
    }
};
